package com.clsclassloder;

import java.io.IOException;
import java.io.InputStream;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class MyJarClassLoader extends ClassLoader {
    private final String jarPath;

    public MyJarClassLoader(String jarPath) {
        this.jarPath = jarPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String jarClassName = name.replace('.', '/').concat(".class");
        try (JarFile jarFile = new JarFile(this.jarPath);) {
            JarEntry jarEntry = jarFile.getJarEntry(jarClassName);
            if (jarEntry == null) {
                throw new ClassNotFoundException();
            }
            InputStream is = jarFile.getInputStream(jarEntry);
            int available = is.available();
            byte[] buffer = new byte[available];
            is.read(buffer);

            return defineClass(name, buffer, 0, available);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        return super.findClass(name);
    }
}
